<template>
  <n-layout has-sider>
    <n-layout-sider>
      <n-menu
        :value="currentValue"
        @update-value="handleUpdateValue"
        :collapsed-width="64"
        :collapsed-icon-size="22"
        :options="menuOptions"
        key-field="path"
        label-field="name"
        children-field="children"
      />
    </n-layout-sider>
    <n-layout />
  </n-layout>
</template>

<script lang="ts" setup>
import { h, ref, onMounted } from "vue";
import { NIcon } from "naive-ui";
import router from "../router/index";

import {
  BookOutline as BookIcon,
  PersonOutline as PersonIcon,
  WineOutline as WineIcon,
  Home,
  LogIn,
} from "@vicons/ionicons5";
import { menuStore } from "@/stores/global";

// const props = defineProps(["menuList"]);
// const props = inject<Ref<string>>("menuList", ref(""));
const MenuStore = menuStore();
const currentValue: any = ref("/home/homeIndex");
const menuOptions: any = ref([]);

const handleUpdateValue = (path: any) => {
  currentValue.value = path;
  router.push({
    path: path,
  });
};

async function renderIcon(icon) {
  const { [icon]: iconComp } = await import("@vicons/ionicons5");
  return () => h(NIcon, null, { default: () => h(iconComp) });
  // return () => h(NIcon, null, { default: () => h(icon) });
}

// 白名单
const whiteRouter: any = ["/home"];

// 路由守卫  权限校验
router.beforeEach((to, from, next) => {
  currentValue.value = to.fullPath; // 菜单激活
  if (localStorage.getItem("token")) {
    return next();
  } else {
    return next("/login");
  }
});

// 添加动态路由
const addRouter = async () => {
  MenuStore.$state.menu.forEach(async (menuList) => {
    var children: any = [];
    var menuChildren: any = [];

    // 假设没子路由抛出异常

    menuList.children.length
      ? menuList.children.forEach(async (menu: any) => {
          console.log(menu.title);

          children.push({
            name: menu.name,
            path: menu.path,
            component: () =>
              import(`../views/${menuList.name}/${menu.name}.vue`),
          });
          menuChildren.push({
            name: menu.title,
            path: `/${menuList.name}/${menu.name}`,
            icon: await renderIcon(menu.icon || "GameController"),
          });
        })
      : [];

    menuOptions.value.push({
      name: menuList.title,
      path: menuList.path,
      icon: await renderIcon(menuList.icon || "GameController"),
      children: menuChildren.length ? menuChildren : null,
    });

    router.addRoute({
      name: menuList.name,
      path: menuList.path,
      children: children.length ? children : null,
    });
  });
};

onMounted(() => {
  // 动态添加路由
  menuOptions.value = [];
  addRouter();
  // console.log(menuOptions.value);
});
</script>
